import Taro, { Config, Component } from '@tarojs/taro'
import { Image, RichText, Text, View } from '@tarojs/components'
import './index.scss'
import { getSharePath } from "@/utils/storage"
import {formatHtml, formatTime} from "@/utils/utils"
import { getNewsType, getNewsDetail } from '@/api/newsApi'
import { Loading } from "@/components/index"
import {APP_NAME} from "@/config/config";

export default class Index extends Component {
  state: any
  config: Config = {
    backgroundTextStyle: "dark",
    navigationBarTitleText: '新闻详情',
  }

  constructor () {
    super(...arguments)
    const { params } = this.$router
    this.state = {
      id: params.id,
      loading: true,
      newsInfo: {},
      typeInfo: {}
    }
  }

  componentWillMount() {
    this.getInfo()
  }

  //  分享小程序
  onShareAppMessage() {
    return { title: APP_NAME, path: getSharePath() }
  }

  //  获取资讯信息
  async getInfo() {
    const { id } = this.state
    const typeRes = await getNewsType()
    const typeList = typeRes.data
    getNewsDetail(id).then(res => {
      const { data } = res
      const ind = typeList.findIndex(i => i.id === data.cid)
      this.setState({
        loading: false,
        newsInfo: res.data,
        typeInfo: typeList[ind]
      })
    })
  }

  render() {
    const { loading, newsInfo, typeInfo } = this.state

    return (<View className='page'>
      {loading && <Loading isCover/>}
      <View className='news-info'>
        <View className='news-title'>{newsInfo.title}</View>
        <View className='d-f a-i-c j-c-b'>
          <View className='type-name t-o-e'>{typeInfo.title}</View>
          <View className='news-time'>{formatTime(newsInfo.createdAt)}</View>
        </View>
        <Image src={newsInfo.coverImg} className='cover-img'/>
        <View className='rich-text-wrap news-content'>
          <RichText nodes={formatHtml(newsInfo.content)} />
        </View>
        <View className='news-foot'>
          <View className='see-number d-f a-i-c'>
            <Text className='bnn-icon m-r-10'>&#xe73d;</Text>{newsInfo.readNumber}
          </View>
        </View>
      </View>
    </View>)
  }
}
